#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <alsa/asoundlib.h>

#include "h264encoder.h"
#include "h264capture.h"
#include "libavstream.h"
#include "libavstream.h"

#include "aacenc_lib.h"


pthread_mutex_t g_avwrite_mutex = PTHREAD_MUTEX_INITIALIZER;

IOTC_Camera *cam;
char *readbuf;

int h264_stream_init()
{
	cam = (IOTC_Camera *)malloc(sizeof(IOTC_Camera));
	if (!cam) 
	{
		printf("malloc camera failure\n");
		return -1;
	}

	memset(cam, 0, sizeof(IOTC_Camera));
	cam->device_name = "/dev/video0";
	cam->buffers = NULL;
	cam->width = 640;
	cam->height = 360;
	cam->display_depth = 5;

	camera_open(cam);
	camera_init(cam);
	camera_capturing_start(cam);
	h264_encoder_init(&cam->encoder, cam->width, cam->height);
	cam->h264_buf = (unsigned char *)  malloc(sizeof(unsigned char ) * cam->width * cam->height * 3);

	return 0;
}

int h264_stream_get(video_frame_info *pv_info)
{
	int readFrame=read_and_encode_frame(cam);
	if(readFrame == 0)
	{
		pv_info->frame_len = cam->encodedLength;
		pv_info->pframe_data = cam->h264_buf;
		//printf("frame_type:%d frame_len:%d i_pts(%lu)  (%d)\n", cam->encoder.picture->i_type, pv_info->frame_len, cam->encoder.picture->i_pts,cam->encoder.nal->i_type);
		if(cam->encoder.nal->i_type == 0x7)
		{
			pv_info->frame_type = I_FRAME;
		}
		else
		{
			pv_info->frame_type = P_FREAME;
		}
		pv_info->width = cam->width;
		pv_info->height = cam->height;
		
	}
}

int h264_stream_deinit()
{
	h264_encoder_uninit(&cam->encoder);

	if(cam->h264_buf!=NULL)
	{
		free(cam->h264_buf);
	}

	camera_capturing_stop(cam);
	camera_uninit(cam);
	camera_close(cam);
	free(cam);
	return 0;
}

int h264_stream_param_get(h264_param *pv_param)
{
	if(pv_param)
	{
		pv_param->width = cam->width;
		pv_param->height = cam->height;
		pv_param->fps = cam->encoder.param->i_fps_num;
		return 0;
	}

	return -1;
}


